<?php
namespace App\Admin\Controllers\OverSeasIn;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\SysArea;
use App\Models\OverSeasIn\Delivery;
use App\Models\OverSeasIn\DeliveryBox;
use App\Models\OverSeasIn\DeliveryDetail;
use App\Models\OverSeasBa\Warehouse;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductPacking;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class OSDropshippingDetailController extends AdminController{

    protected $title = 'CN至海外仓(代发)-发货单明细';

    protected function grid()
    {
        $grid = new Grid(new DeliveryDetail());
        $grid->model()
            ->where('delivery_type', Delivery::OS_DELIVERY_DROPSHIPPING) //代发
            ->collection(function (Collection $collection){
                foreach($collection as $index => $item) {
                    $item->tracking_no = $item->delivery->logistics->tracking_no ?? '';
                    $item->storage_total_num = DeliveryBox::storageTotalNum($item->delivery_no,$item->fnsku);
                }
                return $collection;
            });
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('delivery_no','发货单');
        $grid->column('delivery.batch_no','批次号');
        $grid->column('delivery.area_id','站点')->display(function ($value){
            return SysArea::getSysAreaById($value);
        });
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('skuClassify.title','品类');
        $grid->column('delivery.status','状态')->display(function ($value){
            return Delivery::$_status[$value];
        });
        $grid->column('delivery.transport_status','运输状态')->display(function ($value){
            return Delivery::$_transportStatus[$value];
        });
        $grid->column('fnsku','FNSKU');
        $grid->column('apply_num','数量');
        $grid->column('ship_num','已确定数量');
        $grid->column('storage_total_num','已入库数量');
        $grid->column('delivery.seller_id','销售员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('delivery.warehouse_id','仓库')->display(function ($value){
            return Warehouse::getCodeById($value);
        });
        $grid->column('delivery_cost','发货成本')->display(function ($value){
            return sprintf("%.2f", ($this->ship_num ?? 0) * ($this->unit_price ?? 0));
        });
        $grid->column('delivery.delivered_at','发货时间');
        $grid->column('tracking_no','追踪号');
        $grid->column('delivery.remarks','备注');
        $grid->disableActions();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('overseas-in/os-dropshipping-detail-download'));
        });
        $grid->fixColumns(0,0);
        $grid->disableCreateButton();
        $grid->fixHeader();
        $grid->disableRowSelector();
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('delivery_no','发货单');
                $filter->equal('delivery.batch_no','批次号');
                $filter->equal('delivery.warehouse_id','仓库')->select(Warehouse::options());
                $filter->equal('delivery.area_id','站点')->select(SysArea::options());
            });
            $filter->column(1/3, function ($filter){
                $filter->equal('delivery.seller_id','销售')->select(User::getSellerOptions());
                $filter->equal('delivery.status', '状态')->select(Delivery::$_status);

                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
            $filter->column(1/3, function ($filter){
                $filter->between('delivery.delivered_at', '发货日期')->date();
                $filter->equal('delivery.transport_status', '运输状态')->select(Delivery::$_transportStatus);
                $filter->equal('delivery.logistics_status', '物流状态')->select(Delivery::$_logisticsStatus);
                $filter->equal('delivery.logistics.tracking_no', '追踪号');
            });
        });
        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        //海外仓-发货明细
        $query = DeliveryDetail::query()
            ->where('delivery_type', Delivery::OS_DELIVERY_DROPSHIPPING) //代发
            ->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'delivery'){
                $query->whereHas('delivery', function ($query) use($_filter){
                    foreach ($_filter as $field => $filter){
                        if($field == 'delivered_at'){
                            if(isset($filter['start'])&&$filter['start']){
                                $query->where($field,'>=',$filter['start'] . ' 00:00:00');
                            }
                            if(isset($filter['end'])&&$filter['end']){
                                $query->where($field,'<=',$filter['end'] . ' 23:59:59');
                            }
                        }else{
                            $query->where($field, $filter);
                        }
                    }
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if(in_array($key,['delivery_no'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['发货单','批次号','销售员','目的仓库','发货站点','SKU ID','SKU','产品名称','季节性','品类','状态','运输状态',
            '账号','FNSKU','数量','已确定数量','已入库数量','发货成本','发货时间','备注',
            '追踪号','运费','其他费用','该单平均物流费','该单产品发货重量','该单产品物流费'];
        RExcel::exportCsv('海外仓发货单明细',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        $account = [];
        $seller = [];
        $weight = [];
        foreach ($res as $model){
            $accountId = $model->account_id ?: -1;
            if(!array_key_exists($accountId,$account)){
                $account[$accountId] = SysPlatAccount::getAccountById($accountId);
            }
            $sellerId = $model->delivery->seller_id ?? -1;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            if(!array_key_exists($model->psku_id,$weight)){
                $weight[$model->psku_id] = ProductPacking::getShipWeight($model->psku_id);
            }
            $temp = [
                $model->delivery_no,
                $model->delivery->batch_no ?? '',
                $seller[$sellerId],
                $model->delivery->warehouse->w_code ?? '',
                $model->delivery->area->area ?? '',
                $model->psku_id,
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                $model->skuClassify->season ?? '',
                $model->skuClassify->title ?? '',
                array_key_exists($model->delivery->status ?? 1,Delivery::$_status) ? Delivery::$_status[$model->delivery->status ?? 1] : '',
                array_key_exists($model->transport_status,Delivery::$_transportStatus) ? Delivery::$_transportStatus[$model->delivery->transport_status] : '',
                $account[$accountId],
                $model->fnsku,
                $model->apply_num,
                $model->ship_num,
                DeliveryBox::storageTotalNum($model->delivery_no,$model->fnsku),
                sprintf("%.2f", ($model->ship_num ?? 0) * ($model->unit_price ?? 0)),
                $model->delivery->delivered_at ?? '',
                $model->delivery->remarks ?? '',
                $model->delivery->logistics->tracking_no ?? '',
                $model->delivery->logistics->shipping_fee ?? '',
                $model->delivery->logistics->other_fee ?? '',
                $model->delivery->avg_price ?? '',
                $weight[$model->psku_id],
                $model->logistics_fee,
            ];
            yield $temp;
        }
    }
}
